<template>
  <el-dialog
    v-model="dialogVisible"
    title="智能处理"
    width="90%"
    :before-close="handleClose"
    class="ai-processing-dialog"
  >
    <div v-if="!submission" class="no-submission">
      <el-empty description="未找到提交记录" />
    </div>

    <div v-else class="ai-processing-content">
      <!-- 学生信息 -->
      <div class="student-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学号">
            {{ submission.student_id }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ submission.student_name }}
          </el-descriptions-item>
          <el-descriptions-item label="提交ID">
            {{ submission.submission_id }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(submission.status)">
              {{ getStatusText(submission.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- OCR处理部分 -->
      <div class="ocr-section">
        <div class="section-header">
          <h4>试卷扫描识别</h4>
          <el-button
            type="primary"
            @click="handleStartOCR"
            :disabled="!hasAttachments || ocrStatus === 'PROCESSING'"
            :loading="ocrStatus === 'PROCESSING'"
          >
            {{ getOCRButtonText }}
          </el-button>
        </div>

        <!-- 扫描件展示和OCR结果 -->
        <div v-if="hasAttachments" class="attachments-container">
          <el-row :gutter="20">
            <!-- 左侧图片展示区 -->
            <el-col :span="12">
              <el-tabs v-model="activeAttachmentTab" type="border-card">
                <el-tab-pane
                  v-for="(attachment, index) in attachments"
                  :key="attachment.id"
                  :label="`扫描件 ${index + 1}`"
                  :name="String(index)"
                >
                  <div class="image-preview-container">
                    <el-image
                      :src="attachment.file_path"
                      :preview-src-list="[attachment.file_path]"
                      fit="contain"
                      class="preview-image"
                    >
                      <template #placeholder>
                        <div class="image-placeholder">
                          <el-icon><Picture /></el-icon>
                          <span>加载中...</span>
                        </div>
                      </template>
                      <template #error>
                        <div class="image-error">
                          <el-icon><PictureFilled /></el-icon>
                          <span>加载失败</span>
                        </div>
                      </template>
                    </el-image>
                    <div class="image-actions">
  <el-link
    :href="attachment.file_path"
    target="_blank"
    type="primary"
  >
    <el-icon><Download /></el-icon> 下载原图
  </el-link>
</div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-col>

            <!-- 右侧结果展示区 -->
            <el-col :span="12">
              <el-card class="results-card">
                <template #header>
                  <div class="results-header">
                    <span>OCR识别结果</span>
                    <el-tag v-if="currentAttachment" size="small" :type="getOCRStatusType(currentAttachment.ocr_status)">
                      {{ getOCRStatusText(currentAttachment.ocr_status) }}
                    </el-tag>
                  </div>
                </template>

                <div v-if="currentAttachment" class="result-section">
                  <div v-if="currentAttachment.ocr_status === 'COMPLETED'" class="ocr-content">
                    <pre>{{ currentAttachment.ocr_content }}</pre>
                  </div>
                  <div v-else-if="currentAttachment.ocr_status === 'PROCESSING'" class="processing-status">
                    <el-spinner /> 正在识别中...
                  </div>
                  <div v-else-if="currentAttachment.ocr_status === 'FAILED'" class="error-status">
                    <el-alert
                      title="识别失败"
                      type="error"
                      :closable="false"
                      show-icon
                    />
                  </div>
                  <div v-else class="pending-status">
                    <el-empty description="等待开始识别" />
                  </div>
                </div>
                <div v-else class="no-attachment-selected">
                  <el-empty description="请选择扫描件" />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        <el-empty v-else description="暂无扫描件" />
      </div>

      <!-- AI分析部分 -->
      <div class="ai-section" v-if="ocrCompleted">
        <div class="section-header">
          <h4>AI智能分析</h4>
          <div class="ai-controls">
  <el-select
    v-model="selectedTemplate"
    placeholder="选择分析模板"
    style="width: 200px; margin-right: 10px;"
  >
    <el-option
      v-for="template in aiTemplates"
      :key="template.id"
      :label="template.title"
      :value="template.id"
    />
  </el-select>
  <el-button type="success" @click="templateDialogVisible = true">
    新建模板
  </el-button>
  <el-button
    type="primary"
    @click="handleStartAI"
    :disabled="aiStatus === 'PROCESSING'"
    :loading="aiStatus === 'PROCESSING'"
  >
    {{ getAIButtonText }}
  </el-button>
</div>
        </div>

        <div v-if="currentTemplate" class="template-preview">
  <el-card>
    <template #header>
      <div class="template-header">
        <span>{{ currentTemplate.title }}</span>
        <el-tag size="small">{{ currentTemplate.description }}</el-tag>
      </div>
    </template>
    <pre class="template-content">{{ currentTemplate.content }}</pre>
  </el-card>
</div>

        <el-dialog
  v-model="templateDialogVisible"
  title="新建评分模板"
  width="50%"
>
  <el-form :model="newTemplate" label-width="100px">
    <el-form-item label="模板名称">
      <el-input v-model="newTemplate.title" placeholder="请输入模板名称" />
    </el-form-item>
    <el-form-item label="模板内容">
      <el-input
        v-model="newTemplate.content"
        type="textarea"
        :rows="10"
        placeholder="请输入模板内容"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="templateDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="handleCreateTemplate">保存</el-button>
  </template>
</el-dialog>

        <!-- AI分析结果 -->
        <div v-if="aiResult" class="ai-result">
          <el-card>
            <template #header>
              <div class="ai-result-header">
                <span>分析结果</span>
                <el-tag size="small">{{ formatDate(aiAnalyzedAt) }}</el-tag>
              </div>
            </template>
            <div class="ai-result-content">
              {{ aiResult }}
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, PictureFilled, Download } from '@element-plus/icons-vue'
import axios from 'axios'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  submission: {
    type: Object,
    required: true,
    validator: (value) => {
      return value && value.submission_id && value.student_id && value.student_name;
    }
  }
})
const currentTemplate = ref(null)
const templateDialogVisible = ref(false)
const newTemplate = ref({
  title: '',
  content: '',
})

const emit = defineEmits(['update:visible', 'processed'])

// 基础状态变量
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// OCR相关状态
const activeAttachmentTab = ref('0')
const attachments = ref([])
const ocrStatus = ref('PENDING')

// AI相关状态
const aiStatus = ref('PENDING')
const aiResult = ref('')
const aiAnalyzedAt = ref(null)
const selectedTemplate = ref(null)
const aiTemplates = ref([])

// 计算属性
const hasAttachments = computed(() => {
  return attachments.value && attachments.value.length > 0
})

const currentAttachment = computed(() => {
  const index = parseInt(activeAttachmentTab.value)
  return attachments.value[index]
})

const ocrCompleted = computed(() => {
  return hasAttachments.value && attachments.value.every(att => att.ocr_status === 'COMPLETED')
})

const getOCRButtonText = computed(() => {
  if (!hasAttachments.value) return '无可识别文件'
  switch (ocrStatus.value) {
    case 'PROCESSING':
      return '正在识别...'
    case 'COMPLETED':
      return '重新识别'
    case 'FAILED':
      return '重试识别'
    default:
      return '开始识别'
  }
})

const getAIButtonText = computed(() => {
  switch (aiStatus.value) {
    case 'PROCESSING':
      return '分析中...'
    case 'COMPLETED':
      return '重新分析'
    case 'FAILED':
      return '重试分析'
    default:
      return '开始分析'
  }
})

// 状态处理函数
const getStatusType = (status) => {
  const types = {
    'SUBMITTED': 'success',
    'NOT_SUBMITTED': 'warning',
    'GRADED': 'info',
    'PROCESSING': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'SUBMITTED': '已提交',
    'NOT_SUBMITTED': '未提交',
    'GRADED': '已评分',
    'PROCESSING': '处理中'
  }
  return texts[status] || '未知状态'
}

const getOCRStatusType = (status) => {
  const types = {
    'COMPLETED': 'success',
    'PROCESSING': 'warning',
    'FAILED': 'danger',
    'PENDING': 'info'
  }
  return types[status] || 'info'
}

const getOCRStatusText = (status) => {
  const texts = {
    'COMPLETED': '识别完成',
    'PROCESSING': '识别中',
    'FAILED': '识别失败',
    'PENDING': '待识别'
  }
  return texts[status] || '未知状态'
}

// OCR相关函数
const handleStartOCR = async () => {
  if (!props.submission || !props.submission.submission_id) {
    ElMessage.error('无效的提交ID')
    return
  }

  try {
    const response = await axios.post(
      `/backend/api/exam/submission/${props.submission.submission_id}/trigger_ocr/`,
      {},
      { withCredentials: true }
    )

    if (response.data.success) {
      ocrStatus.value = 'PROCESSING'
      ElMessage.success('OCR处理已启动')
      startOCRPolling()
    } else {
      ElMessage.error(response.data.message || 'OCR处理启动失败')
    }
  } catch (error) {
    console.error('启动OCR失败:', error)
    ElMessage.error('启动OCR失败，请重试')
  }
}

const startOCRPolling = () => {
  if (!props.submission || !props.submission.submission_id) return

  const pollInterval = setInterval(async () => {
    try {
      const response = await axios.get(
        `/backend/api/exam/submission/${props.submission.submission_id}/ocr_status/`,
        { withCredentials: true }
      )

      attachments.value = response.data.attachments || []

      if (response.data.status === 'COMPLETED') {
        ocrStatus.value = 'COMPLETED'
        clearInterval(pollInterval)
        ElMessage.success('OCR处理完成')
      } else if (response.data.status === 'FAILED') {
        ocrStatus.value = 'FAILED'
        clearInterval(pollInterval)
        ElMessage.error('OCR处理失败')
      }
    } catch (error) {
      console.error('获取OCR状态失败:', error)
      clearInterval(pollInterval)
      ocrStatus.value = 'FAILED'
      ElMessage.error('获取OCR状态失败')
    }
  }, 3000)

  // 设置超时
  setTimeout(() => {
    clearInterval(pollInterval)
    if (ocrStatus.value === 'PROCESSING') {
      ocrStatus.value = 'FAILED'
      ElMessage.error('OCR处理超时，请重试')
    }
  }, 5 * 60 * 1000) // 5分钟超时
}

// AI分析相关函数
const handleStartAI = async () => {
  if (!props.submission || !props.submission.submission_id) {
    ElMessage.error('无效的提交ID')
    return
  }

  try {
    const response = await axios.post(
      `/backend/api/exam/ai/analyze/${props.submission.submission_id}/`,
      {
        template_id: selectedTemplate.value
      },
      { withCredentials: true }
    )

    if (response.data.success) {
      aiStatus.value = 'PROCESSING'
      ElMessage.success('AI分析已启动')
      startAIPolling()
    } else {
      ElMessage.error(response.data.message || 'AI分析启动失败')
    }
  } catch (error) {
    console.error('启动AI分析失败:', error)
    ElMessage.error('启动AI分析失败，请重试')
  }
}

const startAIPolling = () => {
  if (!props.submission || !props.submission.submission_id) return

  const pollInterval = setInterval(async () => {
    try {
      const response = await axios.get(
        `/backend/api/exam/ai/result/${props.submission.submission_id}/`,
        { withCredentials: true }
      )

      if (response.data.status === 'COMPLETED') {
        aiStatus.value = 'COMPLETED'
        aiResult.value = response.data.result
        aiAnalyzedAt.value = response.data.analyzed_at
        clearInterval(pollInterval)
        ElMessage.success('AI分析完成')
      } else if (response.data.status === 'ERROR') {
        aiStatus.value = 'FAILED'
        clearInterval(pollInterval)
        ElMessage.error('AI分析失败')
      }
    } catch (error) {
      console.error('获取AI分析结果失败:', error)
      clearInterval(pollInterval)
      aiStatus.value = 'FAILED'
      ElMessage.error('获取AI分析结果失败')
    }
  }, 3000)

  // 设置超时
  setTimeout(() => {
    clearInterval(pollInterval)
    if (aiStatus.value === 'PROCESSING') {
      aiStatus.value =
                aiStatus.value = 'FAILED'
      ElMessage.error('AI分析超时，请重试')
    }
  }, 5 * 60 * 1000) // 5分钟超时
}
const handleCreateTemplate = async () => {
  try {
    const response = await axios.post('/backend/api/exam/ai/templates/save/', {
      title: newTemplate.value.title,
      content: newTemplate.value.content,
    }, {
      withCredentials: true
    })

    if (response.data.success) {
      ElMessage.success('模板创建成功')
      templateDialogVisible.value = false
      // 重新加载模板列表
      await loadAITemplates()
      // 重置表单
      newTemplate.value = {
        title: '',
        content: '',
      }
    } else {
      ElMessage.error(response.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建模板失败:', error)
    ElMessage.error('创建模板失败，请重试')
  }
}


// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 加载AI模板
const loadAITemplates = async () => {
  try {
    const response = await axios.get('/backend/api/exam/ai/templates/', {
      withCredentials: true
    })
    aiTemplates.value = response.data.templates || []
  } catch (error) {
    console.error('获取AI模板失败:', error)
    ElMessage.warning('获取AI模板失败')
  }
}

// 生命周期钩子
onMounted(() => {
  loadAITemplates()
})

watch(() => props.submission, (newVal) => {
  if (newVal && newVal.submission_id) {
    // 重置状态
    ocrStatus.value = 'PENDING'
    aiStatus.value = 'PENDING'
    aiResult.value = ''
    aiAnalyzedAt.value = null
    selectedTemplate.value = null

    // 加载初始数据
    axios.get(`/backend/api/exam/submission/${newVal.submission_id}/ocr_status/`, {
      withCredentials: true
    }).then(response => {
      attachments.value = response.data.attachments || []
      if (response.data.status === 'COMPLETED') {
        ocrStatus.value = 'COMPLETED'
      }
    }).catch(error => {
      console.error('获取OCR状态失败:', error)
    })

    // 加载AI分析结果
    axios.get(`/backend/api/exam/ai/result/${newVal.submission_id}/`, {
      withCredentials: true
    }).then(response => {
      if (response.data.status === 'COMPLETED') {
        aiStatus.value = 'COMPLETED'
        aiResult.value = response.data.result
        aiAnalyzedAt.value = response.data.analyzed_at
      }
    }).catch(error => {
      console.error('获取AI分析结果失败:', error)
    })
  }
}, { immediate: true })

// 在watch中添加模板选择监听
watch(selectedTemplate, async (newVal) => {
  if (newVal) {
    try {
      const response = await axios.get(`/backend/api/exam/ai/templates/${newVal}`, {
        withCredentials: true
      })
      currentTemplate.value = response.data.template
    } catch (error) {
      console.error('获取模板详情失败:', error)
      ElMessage.error('获取模板详情失败')
    }
  } else {
    currentTemplate.value = null
  }
})

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.ai-processing-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.ai-processing-content {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.attachments-container {
  margin: 20px 0;
}

.image-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 20px;
}

.preview-image {
  width: 100%;
  height: 600px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f8f9fa;
}

.image-actions {
  padding: 10px;
  text-align: center;
}

.results-card {
  height: 100%;
  margin-bottom: 20px;
}

.results-card :deep(.el-card__body) {
  padding: 0;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}

.result-section {
  padding: 20px;
}

.ocr-content {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 12px;
  max-height: 520px;
  overflow-y: auto;
}

.ocr-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
  font-size: 13px;
  line-height: 1.5;
}

.processing-status,
.error-status,
.pending-status,
.no-attachment-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: #909399;
}

.image-placeholder,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.image-placeholder .el-icon,
.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.ai-section {
  margin-top: 30px;
}

.ai-controls {
  display: flex;
  align-items: center;
}

.ai-result {
  margin-top: 20px;
}

.ai-result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-result-content {
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.6;
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

/* 滚动条样式美化 */
.ocr-content::-webkit-scrollbar,
.ai-result-content::-webkit-scrollbar {
  width: 6px;
}

.ocr-content::-webkit-scrollbar-thumb,
.ai-result-content::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.ocr-content::-webkit-scrollbar-track,
.ai-result-content::-webkit-scrollbar-track {
  background-color: #f8f9fa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}

/* 添加过渡动画 */
.el-image,
.el-card,
.el-button {
  transition: all 0.3s ease;
}

.el-image:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.results-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.el-button:not(:disabled):hover {
  transform: translateY(-2px);
}

/* 禁用状态样式 */
.el-button.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.template-preview {
  margin-top: 15px;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-content {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 12px;
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
  font-size: 13px;
  line-height: 1.5;
  max-height: 300px;
  overflow-y: auto;
}

.template-content::-webkit-scrollbar {
  width: 6px;
}

.template-content::-webkit-scrollbar-thumb {
  background-color: #909399;
  border-radius: 3px;
}

.template-content::-webkit-scrollbar-track {
  background-color: #f8f9fa;
}
</style>